const Base = require('./base.js');

module.exports = class extends Base {
  async loginByWeixinAction() {
    const code = this.get('code');
    if (think.isEmpty(code)) {
      // const info = await this.model('user').field(['id', 'username', 'nickname', 'gender', 'avatar', 'birthday', 'type']).where({ id: 3 }).find();
      return this.success('登录失败,缺少code');
    }
    const clientIp = this.ctx.ip;
    // 解释用户数据
    const userInfo = await this.service('weixin', 'api').login(code);

    if (think.isEmpty(userInfo)) {
      return this.fail('登录失败');
    }

    // 根据openid查找用户是否已经注册
    let userId = await this.model('user').where({ weixin_openid: userInfo.openid }).getField('id', true);
    if (think.isEmpty(userId)) {
      // 注册
      userId = await this.model('user').add({
        username: '微信用户' + think.uuid(6),
        password: '',
        register_time: ['exp', 'CURRENT_TIMESTAMP()'],
        register_ip: clientIp,
        mobile: '',
        weixin_openid: userInfo.openid,
        avatar: userInfo.headimgurl || '',
        gender: userInfo.sex || 1 // 性别 0：未知、1：男、2：女
      });
    }

    // 查询用户信息
    const newUserInfo = await this.model('user').field(['id', 'name', 'company', 'position', 'avatar', 'birthday', 'mobile', 'is_vip', 'is_auth', 'create_time', 'end_time', 'status', 'nickname', 'weixin']).where({ id: userId }).find();

    // 更新登录信息
    await this.model('user').where({ id: userId }).update({
      last_login_time: parseInt(new Date().getTime() / 1000),
      last_login_ip: clientIp
    });

    const TokenSerivce = this.service('token', 'api');
    const sessionKey = await TokenSerivce.create({ user_id: userId });

    if (think.isEmpty(newUserInfo) || think.isEmpty(sessionKey)) {
      return this.fail('登录失败');
    }

    const wx = await this.model('set').find();

    return this.success({ token: sessionKey, userInfo: newUserInfo, kefu: wx.wx });
  }
  async refreshTokenAction() {
    const city = this.get('city');
    const region = await this.model('region').where({name: city}).find();
    let cityIndex;
    if (think.isEmpty(region)) {
      cityIndex = 3;
    } else {
      cityIndex = region.level;
    }
    const TokenSerivce = this.service('token', 'api');
    const sessionKey = await TokenSerivce.create({ user_id: this.getLoginUserId(), city: cityIndex });

    this.success({ token: sessionKey });
  }
  async updateUserInfoAction() {
    const detail = this.post();
    const data = {
      nickname: detail.nickName,
      avatar: detail.avatarUrl,
      gender: detail.gender
    };

    await this.model('user').where({ id: this.getLoginUserId() }).update(data);
    const userInfo = await this.model('user').field(['id', 'name', 'company', 'position', 'avatar', 'birthday', 'mobile', 'is_vip', 'create_time', 'end_time', 'status', 'nickname']).where({ id: this.getLoginUserId() }).find();

    return this.success(userInfo);
  }

  async getUserPhoneAction() {
    const code = this.post('code');
    const encryptedData = this.post('encryptedData');
    const iv = this.post('iv');
    const phoneInfo = await this.service('weixin', 'api').getUserPhoneData(encryptedData, iv, code);
    if (!phoneInfo) {
      return this.fail({
        code: 408
      });
    }

    await this.model('user').where({ id: this.getLoginUserId() }).update({
      mobile: phoneInfo.phoneNumber
    });
    const userInfo = await this.model('user').where({ id: this.getLoginUserId() }).find();

    return this.success(userInfo);
  }

  async logoutAction() {
    return this.success();
  }
};
